package com.chalk.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.chalk.common.constant.CommonConstants;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.chalk.config.base.BaseController;
import com.chalk.model.SysRole;
import com.chalk.model.SysUser;
import com.chalk.service.SysRoleService;
import com.chalk.service.SysUserService;
import com.chalk.vo.SysRoleVo;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 平台角色信息(SysRole)表控制层
 *
 * @author maxiaoqiang
 * @since 2019-03-22 17:38:25
 */
@Api(value = "平台角色信息接口", tags = "平台角色信息模块")
@RestController
@RequestMapping("/v1/sysRole")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;


    /**
     * 平台角色信息列表
     *
     * @param current 当前页数
     * @param size    每页显示条数
     * @param sysRole 查询实体
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询平台角色信息列表", notes = "查询平台角色信息列表", response = Result.class)
    @GetMapping
    public Result selectAll(Integer current, Integer size, SysRole sysRole) {
        sysRole.setIsDeleted(CommonConstants.IsDeleted.NOTDEL.getValue());

        String username = SecurityContextHolder.getContext().getAuthentication().getName();


        String id = sysRoleService.getRoleByUser(username).getRoleId();
        SysRole role = sysRoleService.selectById(id);

        List <SysRole> sysRoles = new ArrayList <>();

        sysRoles.add(role);
        List <SysRole> sysRoles1 = new ArrayList <SysRole>();
        sysRoles1 = sysRoleService.selectList(new EntityWrapper <SysRole>().eq("f_id", role.getRoleId()).ne("is_deleted",1));
         this.addRole(sysRoles, sysRoles1);
        Page <SysRole> sysRolePage = new Page <>();
        List <SysRole> sysRoleList = new ArrayList <>();
        if(!StringUtil.isNullOrEmpty(sysRole.getName())){
            for (int i = 0; i < sysRoles.size(); i++) {
                if(sysRoles.get(i).getName().equals(sysRole.getName())){
                    sysRoleList.add(sysRoles.get(i));
                }
            }
        }else {
            sysRoleList=sysRoles;
        }
        sysRolePage.setRecords(sysRoleList);
//        sysRolePage.setSize(size);
//        sysRolePage.setCurrent(current);
//        sysRolePage.setTotal(this.sysRoleService.selectCount(new EntityWrapper <SysRole>().ne("is_deleted",1)));
//        sysRole.setFId(id);
//        Page <SysRole> sysRolePage = this.sysRoleService.selectPage(this.getPage(current, size), new EntityWrapper <SysRole>(sysRole));
         /*  List <SysRole> sysRoles = sysRolePage.getRecords();
     for (int i = 0; i < sysRoles.size(); i++) {
            SysRole role = sysRoles.get(i);
            String fId = role.getFId();
            if(fId!=null && fId!=""){
                role.setFName(this.sysRoleService.selectById(fId).getName());
            }
        }*/
        return Result.success(sysRolePage);
    }

    private List <SysRole> addRole(List <SysRole> sysRoles, List <SysRole> sysRoles1) {
        if (sysRoles1 != null && sysRoles1.size() > 0) {
            sysRoles.addAll(sysRoles1);
        }
        for (int i = 0; i < sysRoles1.size(); i++) {
            List <SysRole> sysRoles2 = sysRoleService.selectList(new EntityWrapper <SysRole>().eq("f_id", sysRoles1.get(i).getRoleId()).ne("is_deleted",1));
            addRole(sysRoles, sysRoles2);
        }
        return sysRoles;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询平台角色信息", notes = "查询平台角色信息", response = Result.class)
    @GetMapping("{id}")
    public Result selectOne(
            @ApiParam(name = "id", value = "主键", required = true, example = "1")
            @PathVariable String id) {
        return Result.success(this.sysRoleService.selectById(id));
    }


    /**
     * 保存平台角色信息
     *
     * @param sysRoleVo 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "保存sysRole", notes = "保存sysRole", response = Result.class)
    @PostMapping
    public Result insert(
            @ApiParam(name = "sysRole", value = "传入json格式", required = true)
            @RequestBody SysRoleVo sysRoleVo, BindingResult result) {
        beanValidator(result);
        int count = this.sysRoleService.selectCount(new EntityWrapper <SysRole>()
                .eq("name", sysRoleVo.getName())
                .eq("is_deleted", CommonConstants.IsDeleted.NOTDEL.getValue()));
        if (count > 0) {
            return Result.fail(ResultCode.NAME_REPEAT.msg());
        }
        DateTime date = DateUtil.date();
        sysRoleVo.setCreateTime(date);
        sysRoleVo.setUpdateTime(date);
        return Result.success(this.sysRoleService.insertAndMenu(sysRoleVo));
    }

    /**
     * 修改平台角色信息
     *
     * @param sysRoleVo 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "修改平台角色信息", notes = "修改平台角色信息", response = Result.class)
    @PutMapping
    public Result update(
            @ApiParam(name = "sysRole", value = "传入json格式", required = true)
            @RequestBody SysRoleVo sysRoleVo, BindingResult result) {
        beanValidator(result);
        if (CommonConstants.ROOT_ROLE_ID.equals(sysRoleVo.getRoleId())) {
            return Result.fail(ResultCode.ADMIN_NOT_CHANGE);
        }
        int count = this.sysRoleService.selectCount(new EntityWrapper <SysRole>()
                .eq("name", sysRoleVo.getName())
                .ne("role_id", sysRoleVo.getRoleId())
                .eq("is_deleted", CommonConstants.IsDeleted.NOTDEL.getValue()));
        if (count > 0) {
            return Result.fail(ResultCode.NAME_REPEAT.msg());
        }
        sysRoleVo.setUpdateTime(DateUtil.date());
        return Result.success(this.sysRoleService.updateAndMenu(sysRoleVo));
    }

    /**
     * 逻辑删除平台角色信息
     *
     * @param ids 主键集合
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "批量删除平台角色信息", notes = "批量删除平台角色信息", response = Result.class)
    @DeleteMapping
    public Result delete(
            @ApiParam(name = "ids", value = "传数组", required = true)
            @RequestBody String[] ids) {
        return Result.success(this.sysRoleService.deleteBatchByPrimaryKey(ids));
    }

    private Page <SysRole> getPage(Integer current, Integer size) {
        Page <SysRole> page = new Page <>();
        if (current != null) {
            page.setCurrent(current);
        }
        if (size != null) {
            page.setSize(size);
        }
        return page;
    }

}